<template>
    <div class="user_form_container">
        <el-form ref="userForm" :rules="rules" :model="formData" label-width="100px">
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="绑定员工" prop="group_person_sid" v-if="formData.sid !== 'admin'">
                        <remote-select v-model="formData.group_person_sid" :options="selectProps"
                                       style="width: calc(100% - 28px);" ref="$groupPerson"
                                       @event="handleSelectEvent"/>
                        <el-button type="primary" size="mini" icon="el-icon-refresh"
                                   @click="refreshPerson()"/>
                    </el-form-item>
                    <el-form-item label="账户名" prop="login_id">
                        <el-input v-model="formData.login_id" placeholder="请输入" auto-complete="false"
                                  :disabled="formData.sid === 'admin'" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password" v-show="!isEdit">
                        <el-input type="password" v-model="formData.password" autocomplete="new-password"
                                  placeholder="请输入" auto-complete="false"/>
                    </el-form-item>
                    <el-form-item label="确认密码" prop="repassword" v-show="!isEdit">
                        <el-input type="password" v-model="formData.repassword" autocomplete="new-password"
                                  placeholder="请输入" auto-complete="false"/>
                    </el-form-item>
                    <el-form-item label="角色" prop="role_sid" v-if="formData.sid !== 'admin'">
                        <el-select value-field-name="id" multiple v-model="formData.role_sid_list"
                                   @change="handleChangeRole" style="width: 100%">
                            <el-option v-for="(item, index) in roleList" :key="index"
                                       :label="item.name" :value="item.sid"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="头像" prop="head_pic" style="margin-bottom: 5px;">
                        <UploadCropper ref="uploadCropper" width="100px" height="100px"
                                       :options="uploadCropperOptions" :data="uploadCropperData"
                                       @success="uploadSuccess"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="功能权限" prop="value1">
                        <vTreeEdit ref="functionTree" :options="resourceTreeOptions"
                                   :treeData="resourceZTreeFunctionData"
                                   style="max-height: 200px;"/>
                    </el-form-item>
                    <el-form-item label="客户授权模式" prop="value2" v-if="showClientAuth && false">
                        <el-radio-group v-model="formData.client_auth_mode">
                            <el-radio-button label="none">不控制</el-radio-button>
                            <el-radio-button label="creator">录入者</el-radio-button>
                            <el-radio-button label="group">部门</el-radio-button>
                            <el-radio-button label="setting">授权设置</el-radio-button>
                        </el-radio-group>
                    </el-form-item>
                    <template v-if="formData.client_auth_mode === 'setting'">
                        <el-form-item label="客户授权设置" prop="value2">
                            <el-radio-group v-model="formData.client_auth_setting">
                                <el-radio-button label="type">按客户分组</el-radio-button>
                                <el-radio-button label="client">按客户</el-radio-button>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item prop="value2">
                            <vTreeEdit ref="recordTree" :options="clientTreeOptions" :treeData="clientZTreeData"
                                       @event="handleClientTreeEvent" style="max-height: 200px;" />
                        </el-form-item>
                    </template>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import md5 from 'js-md5';
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import sysResourceApi from "@common/api/system/sysResourceApi";
import baseRelatedPartyApi from "@common/api/base/baseRelatedPartyApi";

export default {
    extends: provide,
    name: "UserForm",
    components: {
        UploadCropper: () => import('@common/components/upload/UploadCropper'),
    },
    props: {
        row: {
            type: Object,
            default: null,
        },
    },
    data () {
        const _this = this;
        let validPassword = (rule, value, callback) => {
            let pattern = /^[A-Za-z0-9+-_.]{1,32}$/;
            if (_this.isEdit) {
                callback();
                return;
            }
            if (_this.$utils.isNotEmpty(value)) {
                if (pattern.test(value)) {
                    if (_this.$utils.isNotEmpty(_this.formData.repassword)) {
                        _this.$refs.userForm.validateField("repassword");
                    }
                    callback();
                } else {
                    callback("最大32位字符，大小写英文、数字或者以下特殊字符（+-_.），不能包含特殊字符");
                }
            } else {
                callback("请输入密码！");
            }
        };
        let validConFirmPassword = (rule, value, callback) => {
            if (_this.isEdit) {
                callback();
                return;
            }
            if (_this.$utils.isNotEmpty(value)) {
                if (_this.formData.password === value) {
                    callback();
                } else {
                    callback("两次录入密码不一致！");
                }
            } else {
                callback("请输入确认密码！");
            }
        };
        return {
            rules: {
                login_id: [
                    { required: true, message: "请输入用户名", trigger: "blur" },
                    {
                        pattern: /^[A-Za-z0-9+-_.]{1,32}$/,
                        message:
                            "最大32位字符，大小写英文、数字或者以下特殊字符（+-_.），不能包含特殊字符",
                    },
                ],
                password: [
                    { required: true, validator: validPassword, trigger: "blur" },
                ],
                repassword: [
                    { required: true, validator: validConFirmPassword, trigger: "blur" },
                ],
            },
            formData: {},
            selectProps: {
                remote: _this.$api.API_FindSysGroupPersons,
                placeholder: '请选择员工',
                optionProps: {
                    label: 'name',
                    value: 'sid',
                },
                filterDataList(list) {
                    return (list || []).filter(item => item.sid !== 'admin');
                },
            },
            roleList: [],
            uploadCropperOptions: {
                dialogOptions: {
                    title: "图标裁剪",
                    visible: false,
                },
                uploadOptions: {
                    accept: 'image/*',
                    limit: 1,
                    tip: '1:1正方形，jpg或png格式图片',
                },
                cropperOptions: {
                    outputType: 'png',
                    autoCropWidth: 100, // 默认生成截图框宽度
                    autoCropHeight: 100, // 默认生成截图框高度
                },
            },
            uploadCropperData: [],
            resourceTree: [],
            resourceTreeOptions: {
                ref: "$resourceTree",
                showCheckbox: true, //节点是否可被选择
                indent: 20, //相邻级节点间的水平缩进，单位为像素
                draggable: false, //是否开启拖拽节点功能
                disabled: true,
            },
            resourceZTreeFunctionData: [],
            clientTreeOptions: {
                ref: "$clientTree",
                showCheckbox: true, //节点是否可被选择
                indent: 20, //相邻级节点间的水平缩进，单位为像素
                draggable: false, //是否开启拖拽节点功能
            },
            clientTreeList: [],
        };
    },
    computed: {
        ...mapState([ 'userInfo', 'global_setting' ]),
        isEdit () {
            return this.$utils.isNotEmpty(this.formData.sid);
        },
        showClientAuth() {
            return this.$utils.isNotEmpty(this.global_setting.enable_client_auth) && this.global_setting.enable_client_auth === 1;
        },
        clientZTreeData() {
            if (this.formData.client_auth_mode === 'setting') {
                let list = this.clientTreeList.map(item => $.extend({}, item));
                if (this.formData.client_auth_setting === 'type') {
                    list = list.map(item => {
                        let obj = $.extend({}, item);
                        delete obj.children;
                        return obj;
                    });
                }
                return list;
            }
            return [];
        },
    },
    watch: {
        row: {
            handler () {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init () {
            const _this = this;
            if (!_this.row) {
                return;
            }
            await _this.storeDispatch('initGlobalSetting');
            if (_this.$refs.userForm) {
                _this.$refs.userForm.clearValidate();
            }
            let role_sid_list = [];
            if (_this.$utils.isNotEmpty(_this.row.role_sid)) {
                if (_this.row.role_sid.indexOf(",") > 0) {
                    role_sid_list = _this.row.role_sid.split(",");
                } else {
                    role_sid_list.push(_this.row.role_sid);
                }
            }
            let client_auth_mode = 'none', client_auth_setting = 'client';
            if (_this.$utils.isNotEmpty(_this.row.client_auth_mode)) {
                client_auth_mode = _this.row.client_auth_mode;
                client_auth_setting = _this.row.client_auth_setting;
            }
            _this.formData = $.extend({}, _this.row, {
                role_sid_list,
                client_auth_mode,
                client_auth_setting,
            });
            if (_this.$utils.isNotEmpty(_this.row.head_pic)) {
                _this.uploadCropperData = [{file_sid: _this.row.head_pic}];
            }
            await _this.initRoleList();
            await _this.initResourceTreeList();
            await _this.initClientTree();
            _this.initResourceTreeCheck();
        },
        handleSelectEvent (event) {
            const _this = this;
            if (event.type === 'change') {
                _this.formData = $.extend({}, _this.formData, {
                    group_person_sid: event.value,
                });
            }
        },
        refreshPerson () {
            if (this.$refs.$groupPerson) {
                this.$refs.$groupPerson.getData(true);
            }
        },
        initResourceTreeList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindSysResourceTree, {
                parentId: '-1'
            }).then(result => {
                let list = sysResourceApi.transferRoleZTreeData(result.data);
                _this.resourceZTreeFunctionData = _this.procTreeDisabled(list);
            }).catch(() => {
            });
        },
        initResourceTreeCheck() {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(_this.formData.role_sid_list)) {
                return;
            }
            this.$nextTick(() => {
                _this.handleChangeRole(_this.formData.role_sid_list);
            });
        },
        procTreeDisabled(datas) {
            const _this = this;
            let list = [];
            if (_this.$utils.isNotEmptyList(datas)) {
                datas.forEach(item => {
                    let obj = $.extend({}, item);
                    obj.disabled = true;
                    if (_this.$utils.isNotEmptyList(item.children)) {
                        obj.children = _this.procTreeDisabled(item.children);
                    }
                    list.push(obj);
                });
            }
            return list;
        },
        initRoleList () {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindSysRoles, {
                nopage: '1',
                with_resource: '1'
            }).then(result => {
                _this.roleList = (result.data || []).map(item => {
                    return {
                        sid: item.sid,
                        name: item.name,
                        resource_list: item.resource_list,
                    };
                });
            }).catch(() => {
            });
        },
        handleChangeRole (val) {
            const _this = this;
            if (_this.$resourceTree) {
                let resourceList = _this.getResuourceList([val]);
                _this.$resourceTree.setCheckedKeys(resourceList);
            }
        },
        getResuourceList(roleSidList) {
            const _this = this;
            let resourceList = [];
            for (let i = 0; i < roleSidList.length; i++) {
                let sid = roleSidList[i];
                let filterList = _this.roleList.filter(item => sid.indexOf(item.sid) !== -1);
                if (_this.$utils.isNotEmptyList(filterList)) {
                    filterList.forEach(item => {
                        resourceList = resourceList.concat(item.resource_list);
                    });
                }
            }
            if (_this.$utils.isNotEmptyList(resourceList)) {
                resourceList = _this.$utils.arrayUnique(resourceList);
            }
            return resourceList;
        },
        uploadSuccess (data) {
            const _this = this;
            let head_pic = '';
            if (_this.$utils.isNotEmptyList(data)) {
                head_pic = data[0].sid;
            }
            _this.formData = $.extend({}, _this.formData, {
                head_pic,
            });
        },
        initClientTree() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindBaseRelatedPartyTypeTreeWithChildren).then(result => {
                _this.clientTreeList = baseRelatedPartyApi.transferClientZTreeData(result.data);
            }).catch(() => {
            });
        },
        handleClientTreeEvent (event) {
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('userForm');
            if (valid) {
                let subData = $.extend({}, _this.formData);
                if (_this.$utils.isEmpty(subData.id)) {
                    subData.password = md5(_this.formData.password);
                }
                subData.name = subData.login_id;
                // if (_this.$clientTree) {
                //     subData.clientList = _this.$clientTree.getCheckedNodes(true).map(item => item.id);
                // }
                delete subData.repassword;
                return _this.saveUserMethod(subData, false, false);
            }
            return valid;
        },
        saveUserMethod(subData, showError = true, addLog = true) {
            const _this = this;
            return _this.fetchData(_this.$api.API_SaveSysUser, subData, showError, addLog).then(result => {
                _this.$message.success('保存成功！');
                if (_this.$utils.isNotEmpty(subData.id) && _this.userInfo.id === subData.id) {
                    let info = $.extend({}, _this.userInfo, (result.data || {}));
                    _this.$store.commit('setState', {
                        propName: 'userInfo',
                        value: info,
                    });
                    _this.$bus.$emit('updateUserHeadPic');
                    _this.$utils.setSessionStorage(_this.$store.state.storageName, info);
                }
                return true;
            }).catch(error => {
                if (error.code === 2100) {
                    let resData = error.data;
                    return _this.$confirm(`员工：${ resData.group_person_name } 已绑定账户：${ resData.login_id }<br/>是否更新绑定账户？`, "提示", {
                        confirmButtonText: "是",
                        cancelButtonText: "否",
                        type: "warning",
                        dangerouslyUseHTMLString: true,
                    }).then(() => {
                        let data = $.extend({}, subData, {
                            update_person: 1,
                        });
                        return _this.saveUserMethod(data);
                    }).catch(() => {
                        return false;
                    });
                } else {
                    _this.$message.error(error.message);
                }
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.user_form_container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}
</style>
